package com.reggie.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.reggie.constant.MessageConstant;
import com.reggie.constant.PasswordConstant;
import com.reggie.constant.StatusConstant;
import com.reggie.context.BaseContext;
import com.reggie.dto.EmployeeDTO;
import com.reggie.dto.EmployeeLoginDTO;
import com.reggie.dto.EmployeePageQueryDTO;
import com.reggie.dto.PasswordEditDTO;
import com.reggie.entity.Employee;
import com.reggie.exception.AccountLockedException;
import com.reggie.exception.AccountNotFoundException;
import com.reggie.exception.PasswordEditFailedException;
import com.reggie.exception.PasswordErrorException;
import com.reggie.mapper.EmployeeMapper;
import com.reggie.result.PageResult;
import com.reggie.result.R;
import com.reggie.service.EmployeeService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 用户登功能
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {

        //1、判断传过来的用户账号和密码，如果为空，则不能登录
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //2、调用mapper查询用户
        Employee employee = employeeMapper.findByName(username);



        //3、判断用户是否存在，如果存在则验证密码是否正确
        if (employee == null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //判断用户是否被锁定
        if (employee.getStatus() == StatusConstant.DISABLE){
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }


        //3.1、正确：登录成功，进入系统

        //设置密码的编码

        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!pwd.equals(employee.getPassword())){

            //提示错误
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_ERROR);
            //3.2、错误：提示语3秒：输入有误请重试，还剩4次！

            //3.3 错误次数限制5次，5次后提示：账号锁定，请1小时后重试！

        }

        //4、登录成功后，跳转至工作台页面

        //5、系统后台不做密码找回，忘记密码联系超级管理员

        return employee;
    }

    /**
     * 添加员工
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {

        System.out.println("Service" + Thread.currentThread().getId());

        //创建一个employee对象
        Employee employee = new Employee();

        //进行属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);

        //将employee的属性全部封装完成
        //设置默认密码和状态
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes(StandardCharsets.UTF_8)));
        employee.setStatus(StatusConstant.ENABLE);

        /*//设置创建时间和更新时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //设置创建人和修改人
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());*/

        //调用mapper实现添加
        employeeMapper.save(employee);
    }

    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {

        //设置分页的参数
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        //调用mapper实现查询
        Page<Employee> page = employeeMapper.findByPage(employeePageQueryDTO);
        //设置返回值对象
        PageResult pageResult = new PageResult(page.getTotal(),page.getResult());
        return pageResult;
    }

    /**
     * 根据id查询数据
     * @param id
     * @return
     */
    @Override
    public Employee findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        //设置密码为null
        employee.setPassword(null);
        return employee;
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        //进行属性拷贝
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);

        /*employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());*/

        //调用mapper实现修改
        employeeMapper.update(employee);
    }

    /**
     * 员工启用和禁用
     * @param status
     * @param id
     */
    @Override
    public void starOrStop(Integer status, Long id) {
        employeeMapper.sterOrStop(status,id);
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     */
    @Override
    public void upPassword(PasswordEditDTO passwordEditDTO) {

        //获取当前用户的id
        Long currentId = BaseContext.getCurrentId();

        //根据id查询数据
        Employee employee = employeeMapper.findById(currentId);

        //判断传过来的旧密码是否正确,如果正确就进行下一步设置
        //前端传过来的密码进行md5编码
        String oldPwd = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes(StandardCharsets.UTF_8));

        //密码不相同，抛出密码修改错误异常
        if (!(oldPwd.equals(employee.getPassword()))){
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
        }

        //调用mapper实现密码修改
        //将秘密加密
        String newPwd = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes(StandardCharsets.UTF_8));
        employeeMapper.upPassword(currentId,newPwd);
    }

}
